import 'package:boss/main.dart';
import 'package:boss/models/coupon.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flustars/flustars.dart' as flustars;
import 'package:flutter/material.dart';

class CouponDetailProvider extends ChangeNotifier {
  Coupon originCoupon;
  Coupon coupon;

  bool get isCouponOn => coupon.usingStatus != Coupon.STATUS_OFF;

  CouponDetailProvider(Coupon coupon) {
    if (coupon == null) {
      this.coupon = Coupon();
      this.coupon.couponType = Coupon.TYPE_CASH;
      this.coupon.usingRange = Coupon.USE_RANGE_DINNER;
      this.coupon.usingRange = '${Coupon.USE_RANGE_DINNER}|${Coupon.USE_RANGE_TAKEOUT}';
    } else {
      this.coupon = Coupon.fromJson(coupon.toJson());
      this.originCoupon = Coupon.fromJson(coupon.toJson());
    }
  }

  String get couponDiscountAmountText {
    if (coupon.couponDiscountAmount == null) {
      return null;
    }

    if (coupon.couponType == Coupon.TYPE_CASH) {
      return AmountUtil.price2String(coupon.couponDiscountAmount);
    } else {
      final data = coupon.couponDiscountAmount / 10;
      return NumberUtil.isInteger(data) ? data.toInt().toString() : data.toString();
    }
  }

  String get usingThresholdText => coupon.usingThreshold == 0 ? null : AmountUtil.price2String(coupon.usingThreshold);

  List<String> get usingRange => coupon.usingRange?.split('|') ?? [];

  String get userShareBonusText => AmountUtil.price2String(coupon.userShareBonus);

  String get waiterShareBonusText => AmountUtil.price2String(coupon.waiterShareBonus);

  DateTime get beginDateTime {
    if (coupon.beginTime == null) {
      return null;
    }

    return flustars.DateUtil.getDateTime(coupon.beginTime);
  }

  DateTime get endDateTime {
    if (coupon.endTime == null) {
      return null;
    }

    return flustars.DateUtil.getDateTime(coupon.endTime);
  }

  String get startTodayText {
    if (coupon.timeLimitType == Coupon.TIME_TODAY) {
      return coupon.relativeDays.toString();
    }

    return null;
  }

  String get startTomorrowText {
    if (coupon.timeLimitType == Coupon.TIME_TOMORROW) {
      return coupon.relativeDays.toString();
    }

    return null;
  }

  void setCouponType(String value) {
    coupon.couponType = value;
    coupon.couponDiscountAmount = null;
    notifyListeners();
  }

  void setCouponDiscountAmount(String value) {
    if (coupon.couponType == Coupon.TYPE_CASH) {
      coupon.couponDiscountAmount = _string2amount(value);
    } else {
      coupon.couponDiscountAmount = _string2discount(value);
    }
    notifyListeners();
  }

  void setUsingThreshold(String value) {
    coupon.usingThreshold = _string2amount(value);
    notifyListeners();
  }

  setCouponUseRange(List<String> selectedItems, String item) {
    coupon.usingRange = selectedItems.join('|');
    notifyListeners();
  }

  void setUserShareBonus(String value) {
    coupon.userShareBonus = _string2amount(value);
    notifyListeners();
  }

  void setWaiterShareBonus(String value) {
    coupon.waiterShareBonus = _string2amount(value);
    notifyListeners();
  }

  void setCouponTotalNum(String value) {
    coupon.couponTotalNum = _string2int(value);
    notifyListeners();
  }

  setTimeLimitType(String value) {
    coupon.timeLimitType = value;
    notifyListeners();
  }

  void setBeginTime(List<DateTime> dateTime) {
    coupon.beginTime = flustars.DateUtil.formatDate(dateTime[0], format: flustars.DateFormats.y_mo_d);
    coupon.endTime = flustars.DateUtil.formatDate(dateTime[1], format: flustars.DateFormats.y_mo_d);

    setTimeLimitType(Coupon.TIME_ABSOLUTELY);
  }

  void setStartToday(String value) {
    coupon.relativeDays = _string2int(value);
    notifyListeners();
  }

  void setStartTomorrow(String value) {
    coupon.relativeDays = _string2int(value);
    notifyListeners();
  }

  void setPersonLimitNum(String value) {
    coupon.personLimitNum = _string2int(value);
    notifyListeners();
  }

  void setAdvanceNoticeDays(String value) {
    coupon.advanceNoticeDays = _string2int(value);
    notifyListeners();
  }

  void setShareMessage(Map<String, dynamic> message) {
    if (message == null) return;

    coupon.shareTitle = message['title'];
    coupon.shareImageUrl = message['imageUrl'];
    notifyListeners();
  }

  Future<void> saveCoupon() async {
    try {
      _check();

      showLoadingToast();

      if (coupon.waiterShareBonus == null) {
        coupon.waiterShareBonus = 0;
      }
      if (coupon.userShareBonus == null) {
        coupon.userShareBonus = 0;
      }

      final res = await (originCoupon == null ? api.addCoupon(coupon) : api.updateCoupon(coupon));

      if (!res.successful()) {
        throw res.msg;
      }

      toast(originCoupon == null ? '新增成功' : '修改成功');

      Navigator.pop(GlobalPageContext.instance.context);
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }

  Future closeCoupon() async {
    try {
      showLoadingToast();

      originCoupon.usingStatus = Coupon.STATUS_OFF;

      final res = await api.updateCoupon(originCoupon);

      if (!res.successful()) {
        toast(res.msg);
        return;
      }

      toast('该优惠券已结束');

      coupon.usingStatus = Coupon.STATUS_OFF;
      notifyListeners();
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }

  copyCoupon() {
    coupon = Coupon.fromJson(coupon.toJson());
    coupon.usingStatus = null;
    coupon.id = null;
    originCoupon = null;
    notifyListeners();
  }

  _check() {
    if (coupon.couponName == null || coupon.couponName == '') {
      throw '请输入优惠券名称';
    }
    if (coupon.couponName.length > 10) {
      throw '优惠券名称最多输入10位';
    }
    if (coupon.couponDiscountAmount == null || coupon.couponDiscountAmount == 0) {
      throw '请输入代金券';
    }
    if (coupon.couponDiscountAmount.toString().length > 5 && coupon.couponType == Coupon.TYPE_CASH) {
      throw '代金券最多输入5位';
    }
    if ((coupon.couponDiscountAmount < 0 || coupon.couponDiscountAmount > 99) && coupon.couponType == Coupon.TYPE_DISCOUNT) {
      throw '折扣券应大于0折并且小于9.9折';
    }
    if (coupon.usingThreshold != null && coupon.usingThreshold.toString().length > 9) {
      throw '使用门槛最多输入9位';
    }
    if (coupon.usingRange == null || coupon.usingRange == '') {
      throw '使用范围不能为空';
    }
    if (coupon.timeLimitType == null) {
      throw '请选择使用期限';
    }
    if (coupon.timeLimitType == Coupon.TIME_ABSOLUTELY && (coupon.beginTime == null || coupon.endTime == null)) {
      throw '请选择使用期限';
    }
    if (coupon.timeLimitType == Coupon.TIME_TODAY && coupon.relativeDays == null) {
      throw '请输入使用期限';
    }
    if (coupon.timeLimitType == Coupon.TIME_TOMORROW && coupon.relativeDays == null) {
      throw '请输入使用期限';
    }
    if (coupon.couponTotalNum != null && coupon.couponTotalNum.toString().length > 9) {
      throw '发劵总量最多输入9位';
    }
    if (coupon.shareTitle == null || coupon.shareTitle == '') {
      throw '请输入分享标题';
    }
    if (coupon.shareImageUrl == null) {
      throw '请选择分享图片';
    }
    if (flustars.TextUtil.isEmpty(coupon.couponDescribe)) {
      throw '请输入优惠券描述';
    }
    if (coupon.couponDescribe.length > 120) {
      throw '优惠券描述最多输入120位';
    }
  }

  int _string2int(String value) {
    if (value == null || value == '') {
      return null;
    } else {
      return int.parse(value);
    }
  }

  int _string2discount(String value) {
    if (value == null || value == '') {
      return null;
    } else {
      return flustars.NumUtil.multiply(double.parse(value), 10).toInt();
    }
  }

  int _string2amount(String value) {
    if (value == null || value == '') {
      return 0;
    } else {
      return AmountUtil.string2Price(value);
    }
  }

  void setCouponDescribe(String value) {
    coupon.couponDescribe = value;
    notifyListeners();
  }
}
